//
//  ViewController.m
//  CoreAnimationDemo
//
//  Created by 王亮 on 2017/8/7.
//  Copyright © 2017年 王亮. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<CALayerDelegate>

@property (nonatomic, strong)UIView *layerView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor grayColor];
    self.layerView = [[UIView alloc] init];
    self.layerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.layerView];
    
    //init sub layer
    CALayer *blueLayer = [CALayer layer];
    blueLayer.frame = CGRectMake(50, 50, 100, 100);
    blueLayer.backgroundColor = [UIColor blueColor].CGColor;
    blueLayer.delegate = self;
    blueLayer.contentsScale = [UIScreen mainScreen].scale;
//    [self.layerView.layer addSublayer:blueLayer];
    
//    [blueLayer display];
    
    //set layer contents
    UIImage *image = [UIImage imageNamed:@"timg"];
    self.layerView.layer.contents = (__bridge id)(image.CGImage);
    self.layerView.layer.contentsGravity = kCAGravityCenter;
    
    self.layerView.layer.contentsScale = [UIScreen mainScreen].scale;
//    self.layerView.layer.masksToBounds = YES;
    
    ///set layer contentrect
//    self.layerView.layer.contentsRect = CGRectMake(0, 0, 0.5, 0.5);
    
    /*add affine animation*/
    CGAffineTransform affineTf = CGAffineTransformMakeRotation(M_PI_4);
//    self.layerView.layer.affineTransform = affineTf;
    
//    //手动创建仿射变换的平移变换矩阵,水平移动tx，垂直移动ty
//    CGFloat tx = 100;
//    CGFloat ty = 100;
//    CGAffineTransform affineTf = CGAffineTransformIdentity;
//    affineTf.a = 1;
//    affineTf.c = 0;
//    affineTf.tx = tx;
//    affineTf.b = 0;
//    affineTf.d = 1;
//    affineTf.ty = ty;
//    self.layerView.layer.affineTransform = affineTf;
    
    CATransform3D tf3D = CATransform3DIdentity;
    tf3D.m34 = - 1.0 / 500.0;
    tf3D = CATransform3DRotate(tf3D, M_PI, 0, 1, 0);
    self.layerView.layer.transform = tf3D;
    self.layerView.layer.doubleSided = YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.layerView.frame = CGRectMake(0, 0, 200, 200);
    self.layerView.center = self.view.center;
}

#pragma mark - CALayerDelegate

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    CGContextSetLineWidth(ctx, 10.0);
    CGContextSetStrokeColorWithColor(ctx, [UIColor redColor].CGColor);
    CGContextStrokeEllipseInRect(ctx, layer.bounds);
}

@end
